<template>
  <div>
    <el-card>
      <div>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="品牌名称">
            <el-input v-model="searchInfo.name" placeholder="请输入品牌名称" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" :icon="Search" @click="initVue">搜索</el-button>
            <el-button size="small" :icon="Refresh" @click="refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button size="small" type="primary" :icon="Plus" @click="showDialog" plain>新增</el-button>
        <!--        <el-button size="small" type="success" :icon="Edit" plain>修改</el-button>-->
        <el-button size="small" type="danger" :icon="Delete" @click="delBrand" plain>批量删除</el-button>
      </div>
      <div style="margin-top: 10px">
        <el-table :data="brand.brandPageList" style="width: 100%" @selection-change="tableChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="品牌名称" property="name" width="200"/>
          <el-table-column label="品牌图标" property="logo">
            <template #default="scope">
              <img :src="scope.row.logo" style="width: 40px;height: 40px"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" property="createTime"/>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" text :icon="Edit" @click="showBrand(scope.row)">修改
              </el-button>
              <el-button size="small" type="danger" text :icon="Delete" @click="delBrand(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <pagination
            v-show="searchInfo.total > 0"
            :total="searchInfo.total"
            v-model:page="searchInfo.pageNum"
            v-model:limit="searchInfo.pageSize"
            @pagination="initVue"/>
      </template>
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="title" width="500">
      <el-form :model="pBrand" :rules="myRules" ref="addOrUpdateForm">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="pBrand.name" placeholder="请输入品牌名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload
              class="avatar-uploader"
              :action="imgUpload.urls"
              :headers="imgUpload.headers"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
            <img v-if="pBrand.logo" :src="pBrand.logo" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
          <el-button type="success" @click="addOrUpdate()">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Refresh, Delete, Plus, Edit, Search} from '@element-plus/icons-vue'
import {reactive, ref, onMounted} from "vue";
import {listBrands, saveOrUpdate, delBrands} from '@/api/product/brand.js'
import {brandPinia} from "@/store/product/brandPinia.js";
import {ElMessageBox, ElMessage} from "element-plus";
import {getToken} from "@/utils/auth.js";

let brand = brandPinia()
/*================================分页查询================================*/
//搜索条件
let searchInfo = reactive({
  name: '',
  pageNum: 1,
  pageSize: 5,
  total: 0
})
//分页查询品牌列表
let initVue = async () => {
  let {rows, total} = await listBrands(searchInfo)
  brand.brandPageList = rows
  searchInfo.total = total
}
//页面挂载完毕立即执行的钩子函数
onMounted(() => {
  initVue()
})
//重置
let refresh = () => {
  searchInfo.name = ''
  searchInfo.pageNum = 1
  searchInfo.pageSize = 5
  searchInfo.total = 0
  initVue()
}
/*================================批量删除================================*/
let ids = ref([])
let tableChange = (newSelection) => {
  ids.value = newSelection.map(item => item.id)
}
let delBrand = async (row) => {
  let brandIds = row.id || ids.value
  ElMessageBox.confirm('是否删除?', '提示', {confirmButtonText: '确认', cancelButtonText: '取消'}).then(async () => {
    try {
      await delBrands(brandIds)
      ElMessage.success('删除成功')
      await initVue()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.warning('取消删除')
  })
}
/*================================添加|修改================================*/
//弹框标题
let title = ref()
// 数据模型
let pBrand = reactive({
  id: null,
  name: '',
  logo: ''
})
//对话框默认不弹出
let dialogFormVisible = ref(false)
//对话框弹出的方法
let showDialog = () => {
  title.value = '新增品牌'
  clearDialog()
  dialogFormVisible.value = true
}
//清空对话框
let clearDialog = () => {
  pBrand.id = 0
  pBrand.name = ''
  pBrand.logo = ''
}
//数据模型规则
let myRules = reactive({
  name: [
    {required: true, message: '请输入品牌名称', trigger: 'blur'},
    {min: 2, max: 10, message: '品牌名称在2-10个字符之间', trigger: 'blur'}
  ],
  logo: [
    {required: true, message: '请上传品牌图标', trigger: 'blur'}
  ]
})
//上传图片数据
let imgUpload = reactive({
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken()
  },
  // 图片上传的方法地址:
  urls: "http://localhost:8080/file/upload"
})
//上传图片前
const beforeUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传的图标必须是JPG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图标大小不能超过2MB!')
    return false
  }
  return true
}
//上传成功设置
function handleUploadSuccess(response) {
  pBrand.logo = response.data.url
  ElMessage.success('上传成功')
}
//删除|修改 表单
let addOrUpdateForm = ref()
//删除|修改 方法
let addOrUpdate = async () => {
  await addOrUpdateForm.value.validate()
  try {
    await saveOrUpdate(pBrand)
   // ElMessage.success( pBrand.id === null || pBrand.id === '' ? '添加品牌成功' : '修改品牌成功')
    ElMessage.success('操作成功')
    dialogFormVisible.value = false
    await initVue()
  } catch (e) {
    ElMessage.error(pBrand.id == null ? '添加品牌失败' : '修改品牌失败')
  }
}
//回显
let showBrand = (row) => {
  dialogFormVisible.value = true
  title.value = '修改品牌'
  Object.assign(pBrand, row)
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>


